<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\cms\controller\meetingInvitationLetter;

use plugin\saiadmin\basic\BaseController;
use app\cms\logic\meetingInvitationLetter\ProjectMeetingInvitationLetterLogic;
use app\cms\model\project_meeting_invitation\ProjectMeetingInvitationSpeaker;
use app\cms\validate\meetingInvitationLetter\ProjectMeetingInvitationLetterValidate;
use support\Log;
use support\Request;
use support\Response;

/**
 * 邀请函控制器
 */
class ProjectMeetingInvitationLetterController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new ProjectMeetingInvitationLetterLogic();
        $this->validate = new ProjectMeetingInvitationLetterValidate;
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['status', ''],
            ['is_display', ''],
        ]);
        $query = $this->logic->search($where);
        $data = $this->logic->getList($query);
        return $this->success($data);
    }


    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $id = $request->input('id', '');

        $data = $request->post();

        Log::info('保存数据：' . json_encode($data));
        unset($data['id']);

        if (!empty($id)) {
            $info = $this->logic->find($id);
            if (!$info) {
                return $this->fail('没有找到该数据');
            }
            $result = $this->logic->update($data, [$this->pk => $id]);
        } else {

            $result = $this->logic->save($data);
            if ($result) {
                $invitation_speaker_id = $data['invitation_speaker_id'];
                ProjectMeetingInvitationSpeaker::where('id', $invitation_speaker_id)->setInc('is_fill_info', 1);
            }
        }
        Log::info('返回结果：' . json_encode($result));
        if ($result) {
            // $res = $this->afterChanges($data);
            $res = $this->logic->order('id', 'desc')->find();
            return $this->success(['id' => $id ? $id : $res->id], '操作成功');
        } else {
            return $this->fail('操作失败');
        }
    }
}
